<template>
  <Modal
    loading
    closable
    :value="modal"
    ref="menuAuth"
    width="400px"
    :mask-closable="false"
    :closable="false"
    scrollable
  >
    <!--头部插槽-->
    <p slot="header">
      <Icon type="ios-eye"></Icon>
      <span class="text-primary">分配 <span class="select-title">{{roleName}}</span> 的菜单权限</span>
    </p>
    <Row class="tree-menu">
      <Tree ref="menuTree" show-checkbox :data="menuTree" :render="renderContent"/>
      <Spin size="large" fix v-if="spinShow"></Spin>
    </Row>
    <div slot="footer">
      <Button size="default" @click="toggleSelected(menuTree,checkedAll)">全选/反选</Button>
      <Dropdown @on-click="dispatchActions" class="space-left-mini">
        <Button size="default" type="default">
          更多操作
          <Icon type="ios-arrow-down"/>
        </Button>
        <DropdownMenu slot="list">
          <DropdownItem v-for="item in dropDownSelect" value="item.value" :name="item.value" :key="item.value">{{
            item.label }}
          </DropdownItem>
        </DropdownMenu>
      </Dropdown>
      <Button size="default" @click="closeMenuAuth" style="margin-left: 8px">取消</Button>
      <Button type="primary" size="default" style="margin-left: 8px" @click="submit()">提交</Button>
    </div>

  </Modal>
</template>

<script>
  import {getRoleMenuTree, updateMenuAuthByRoleId} from '@/api/menu'


  export default {
    name: "menuauth",
    data: () => ({
      rolemgt: {},
      open: false,
      roleId: "",
      roleName: "",
      searchWord: "",
      expandLevel: "",
      spinShow: false,
      dropDownSelect: [
        {
          value: 'refresh',
          label: '刷新',
        },
        {
          value: 'rollall',
          label: '收合所有',
        },
        {
          value: 'openone',
          label: '仅展开一级'
        },
        {
          value: 'opentwo',
          label: '仅展开两级'
        },
        {
          value: 'openall',
          label: '展开所有'
        }
      ],
      menuTree: [],
      checkedAll: true,
    }),
    methods: {
      initMenuNodes() {
        this.spinShow = true;
        this.menuTree = [];
        let menuName = this.searchWord;
        let roleId = this.roleId;
        getRoleMenuTree({menuName, roleId}).then(res => {
          this.spinShow = false;
          const data = res.data;
          this.menuTree.push(...data);
        }).catch(err => {
          this.spinShow = false;
          console.error("获取菜单列表信息出错! " + err)
        })
      },
      initMenuAuth() {
        this.roleId = this.rolemgt.clickedRow.id;
        this.roleName = this.rolemgt.clickedRow.name;
        this.checkedAll = true;
        this.initMenuNodes();
      },
      submit() {
        let _that = this;
        let menuIds = this.geCheckedMenuIds().join(",");
        let roleId = this.roleId;
        updateMenuAuthByRoleId({menuIds, roleId}).then(res => {
          let data = res.data;
          let message = data.message;
          let code = data.code;
          if (code === 200) {
            _that.closeMenuAuth();
            this.$Message.success(message);
            this.rolemgt.calcPages();
            this.rolemgt.initRoleTable();
          }
          if (code === 500) {
            this.$Message["error"]({background: true, content: message});
          }
        }).catch(err => {
          console.error("保存菜单权限时，出现错误" + err)
        })
      },
      geCheckedMenuIds() {
        let checkedNodes = this.$refs.menuTree.getCheckedNodes();
        const menuIds = [];
        checkedNodes.forEach(item => {
          if (item) menuIds.push(item.id);
        });
        return menuIds;
      },
      closeMenuAuth() {
        this.open = false;
        this.clearMenuInfo();
      },
      clearMenuInfo() {
        this.roleId = "";
        this.roleName = "";
      },
      refreshNodes() {
        this.initMenuNodes(this.searchWord);
      },
      /**
       *  收合所有
       * @param treeNodes  当前的菜单树
       * @param type rollall openone opentwo openall
       */
      roll(treeNodes, type) {
        let _that = this;
        if (!!treeNodes) {
          treeNodes.forEach(node => {
            _that.expandLevel = node.level;
            node.expand = false;
            if (type === 0) {
              node.expand = false;
            } else {
              if (_that.expandLevel > (type - 1)) {
                return;
              }
              node.expand = true;
            }
            if (node.children && node.children.length > 0) {
              this.roll(node.children, type)
            }
          });
        }
        _that.expandLevel = "";
      },
      dispatchActions(name) {
        //请求分发
        switch (name) {
          case "refresh":
            this.refreshNodes();
            break;
          case "rollall":
            this.roll(this.menuTree, 0);
            break;
          case "openone":
            this.roll(this.menuTree, 1);
            break;
          case "opentwo":
            this.roll(this.menuTree, 2);
            break;
          case "openall":
            this.roll(this.menuTree, 3);
            break;
          default:
            this.$Message["info"]({background: true, content: '正在努力开发中...'});
            break;
        }
      },
      renderContent(h, {root, node, data}) {
        let level = node.node.level;
        return h('span', {
          style: {
            display: 'inline-block',
            width: '100%'
          }
        }, [
          h('span', [
            h('Icon', {
              props: {
                type: level === 0 ? 'md-paper-plane' : level === 1 || level === 2 ? 'md-reorder' : level === 3 ? 'md-radio-button-on' : 'ios-help-circle-outline'
              },
              style: {
                marginRight: '8px'
              }
            }),
            h('span',
              {
                style: {
                  display: "inline-block",
                  cursor: "pointer",
                  background: node.node.selected ? "#d5e8fc" : "#fff", //根据选中状态设置样式
                  color: node.node.selected ? "#515a6e" : "#515a6e",
                  borderRadius: "3px",
                  padding: "3px"
                },
                on: {
                  click: () => {
                    if (!node.node.selected)
                      this.$refs.menuTree.handleSelect(node.nodeKey); //手动选择树节点
                  }
                }
              }, data.title)
          ])

        ]);
      },
      toggleSelected(menuTree, checkVal) {
        menuTree.forEach((item) => {
          // 选中值
          item.checked = checkVal;
          // 如果有子节点，递归
          if (item.children) {
            this.toggleSelected(item.children, checkVal);
          }
        });
        this.checkedAll = !checkVal;
      }
    },
    computed: {
      modal() {
        return this.open;
      },
    },
    mounted() {
      this.rolemgt = this.$parent.$parent;
    }
  }
</script>

<style scoped>

</style>
